import axios from 'axios'
import store from './store'
import * as types from './types'
import router from '@/router'

// http request 拦截器
axios.interceptors.request.use(
  config => {
    if (store.state.jwt) {
      config.headers.Authorization = `Bearer ${store.state.jwt}`
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)
// http response 拦截器
axios.interceptors.response.use(
  res => {
    return res
  },
  error => {
    if (error.response && error.response.status === 401) {
      // 401 清除token信息并跳转到登录页面
      store.commit(types.LOGOUT)
      router.replace({
        path: '/account/login',
        query: {redirect: router.currentRoute.fullPath}
      })
      return Promise.reject(new Error('请先登录！'))
    } else {
      return Promise.reject(error.response.data)
    }
  }
)
axios.defaults.timeout = 10000
// axios.defaults.baseURL = 'https://exam.nicesite.vip/api'
axios.defaults.baseURL = 'http://localhost:8200/api'
export default axios
